# coding: utf8
'''日期时间类处理通用方法'''
import datetime as dt
from datetime import date, datetime

def mysql_time_to_datatime(mysql_time, take_out_year=False):
	'''转换mysql数据库时间为日期字符串'''
	if isinstance(mysql_time, str):
		mysql_time = datetime.strftime(mysql_time, "%Y-%m-%d %H:%M:%S")
	if take_out_year:
		return mysql_time.strftime("%m/%d %H:%M")
	return mysql_time.strftime("%Y/%m/%d %H:%M")

def mysql_time():
	'''返回数据库日期时间(到秒),用于记录实时保存时间'''
	return datetime.now().strftime('%Y-%m-%d %H:%M:%S')

def local_date():
	'''返回当天日期(到天)'''
	return datetime.now().date()


def time_span(start_time, end_time=None):
	'''计算已经过去多长时间, 时间跨度'''
	if end_time is None:
		end_time = datetime.now()

	delta = end_time - start_time

	if delta.days >= 365:
		return '%d年前' % (delta.days / 365)

	elif delta.days >= 30:
		return '%d个月前' % (delta.days / 30)

	elif delta.days > 0:
		return '%d天前' % delta.days

	elif delta.days < 0 or delta.seconds == 0:
		return "现在"

	elif delta.seconds < 60:
		return "%d秒前" % delta.seconds

	elif delta.seconds < 60 * 60:
		return "%d分钟前" % (delta.seconds / 60)

	else:
		return "%d小时前" % (delta.seconds / 60 / 60)

def time_differ(start_time, end_time=None):
	'''计算时差'''
	if end_time is None:
		end_time = datetime.now()

	delta = end_time - start_time

	if delta.days >= 365:
		return '%d年' % (delta.days / 365)

	elif delta.days >= 30:
		return '%d个月' % (delta.days / 30)

	elif delta.days > 0:
		return '%d天' % delta.days

	elif delta.days < 0 or delta.seconds == 0:
		return "0秒"

	elif delta.seconds < 60:
		return "%d秒" % delta.seconds

	elif delta.seconds < 60 * 60:
		return "%d分钟" % (delta.seconds / 60)

	else:
		return "%d小时" % (delta.seconds / 60 / 60)


def increase_time_in_now(num_time, unit_time):
	'''当前日期下增加时间'''
	format_type = '%Y-%m-%d %H:%M:00'
	return eval('(datetime.now()+dt.timedelta(%s=%d)).strftime(format_type)'
					% (str(unit_time), int(num_time)))
